package com.leyou.page.service;

import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.item.vo.SpecGroupDTO;
import com.leyou.item.vo.SpuDTO;

import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.GoodsClient;
import com.leyou.page.client.SpecificationClient;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PageService {

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private SpecificationClient specificationClient;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     *
     */
    public Map<String, Object> loadModel(Long spuId) {

        Map<String, Object> model = new HashMap<>();
        // 查询spu
        SpuDTO spuDTO = goodsClient.querySpuById(spuId);

        // 查询skus
        List<Sku> skus = spuDTO.getSkus();

        // 查询详情
        SpuDetail spuDetail = spuDTO.getSpuDetail();

        // 查询brand
        Brand brand = brandClient.queryBrandById(spuDTO.getBrandId());

        // 查询商品分类
        List<Category> categories = categoryClient.quryCategoryByIds(Arrays.asList(spuDTO.getCid1(), spuDTO.getCid2(), spuDTO.getCid3()));
        // 查询规格参数
        List<SpecGroupDTO> groupDTOS = specificationClient.queryGroupByCid(spuDTO.getCid3());

        model.put("spu", spuDTO);
        model.put("skus", skus);
        model.put("detail", spuDetail);
        model.put("brand", brand);
        model.put("categories", categories);
        model.put("specs", groupDTOS);
        return model;
    }

    public void createHtml(Long spuId) {
        // 上下文
        Context context = new Context();
        context.setVariables(loadModel(spuId));

        // 输出流
        File desc = new File("/user/upload", spuId + ".html");

        if (desc.exists()) {
            desc.delete();
        }

        try (PrintWriter printWriter = new PrintWriter(desc, "UTF-8")) {

            //生成 thml
            templateEngine.process("item", context, printWriter);
        } catch (Exception e) {
            log.error("[静态页服务] 生成静态页异常!");
        }

    }

    public void deleteHtml(Long spuId) {

        // 输出流
        File desc = new File("/user/upload", spuId + ".html");

        if (desc.exists()) {
            desc.delete();
        }
    }
}
